package io.rehuo.modules.app.interceptor;


import io.jsonwebtoken.Claims;
import io.rehuo.common.exception.RRException;
import io.rehuo.common.utils.IPUtils;
import io.rehuo.modules.app.annotation.Login;
import io.rehuo.modules.app.annotation.RequestLimit;
import io.rehuo.modules.app.entity.TimeBean;
import io.rehuo.modules.app.utils.JwtUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 权限(Token)验证
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private JwtUtils jwtUtils;

    public static final String USER_KEY = "userId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }

        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method mt = handlerMethod.getMethod();
            //获取是否含有注解
            RequestLimit methodAnnotation = mt.getAnnotation(RequestLimit.class);
            //获取 类中是否包含注解，也就是controller 是否有注解
            RequestLimit classAnnotation = mt.getDeclaringClass().getAnnotation(RequestLimit.class);
            // 如果 方法上有注解就优先选择方法上的参数，否则类上的参数
            RequestLimit requestLimit = methodAnnotation != null ? methodAnnotation : classAnnotation;
            if (requestLimit != null) {
                if (isLimit(request, requestLimit)) {
//                    Object tempObj = request.getSession().getAttribute(request.getServletPath() + request.getSession().getId());
//                    TimeBean timeBean = (TimeBean) tempObj;
                    throw new RRException("接口调用过于频繁");
                }
            }
        }

        if (annotation == null) {
            return true;
        }

        //获取用户凭证
        String token = request.getHeader(jwtUtils.getHeader());
//        if (StringUtils.isBlank(token)) {
//            token = request.getParameter(jwtUtils.getHeader());
//        }

        //凭证为空
        if (StringUtils.isBlank(token)) {
            throw new RRException(jwtUtils.getHeader() + "Không có sản phẩm nào", HttpStatus.UNAUTHORIZED.value());
        }

        Claims claims = jwtUtils.getClaimByToken(token);
        if (claims == null || jwtUtils.isTokenExpired(claims.getExpiration())) {
            throw new RRException(jwtUtils.getHeader() + "Vô hiệu, hãy đăng nhập lại", HttpStatus.UNAUTHORIZED.value());
        }

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(USER_KEY, Long.parseLong(claims.getSubject()));

        return true;
    }

    /**
     * 判断请求是否受限
     *
     * @param request
     * @param requestLimit
     * @return
     * @deprecated 受限的条件：
     * 一、当限制时间内调用次数超过预设值，调用会受限。
     * 二、当限制时间的调用次数已经达到预设值，须等限制时间结束后才能重新调用
     */
    public boolean isLimit(HttpServletRequest request, RequestLimit requestLimit) {
        String limitKey = request.getServletPath() + request.getSession().getId();
        Object tempObj = request.getSession().getAttribute(limitKey);
        if (tempObj == null) {
            TimeBean timeBean = new TimeBean();
            timeBean.setCount(1);
            timeBean.setIp(IPUtils.getIpAddr(request));
            Long curTime = System.currentTimeMillis();
            timeBean.setStartTime(curTime);
            timeBean.setCurTime(curTime);
            timeBean.setNextTime(curTime + requestLimit.second() * 1000);
            request.getSession().setAttribute(limitKey, timeBean);
            request.getSession().setMaxInactiveInterval(60);
        } else {
            TimeBean temp = (TimeBean) tempObj;
            Long curTime2 = System.currentTimeMillis();
            Long timeR = curTime2 - temp.getStartTime();
            //当限制时间内调用次数超过预设值，调用会受限。
            boolean con1 = temp.getCount() + 1 > requestLimit.maxCount() && timeR < requestLimit.second() * 1000;
            //当限制时间的调用次数已经达到预设值，须等限制时间结束后才能重新调用
            boolean con2 = temp.getCount() + 1 > requestLimit.maxCount() && temp.getNextTime() > curTime2;
            if (con1 || con2) {
                return true;
            } else if (temp.getCount() + 1 > requestLimit.maxCount() && temp.getNextTime() <= curTime2) {
                temp.setCount(1);
                temp.setCurTime(System.currentTimeMillis());
                temp.setStartTime(temp.getNextTime());
                temp.setNextTime(temp.getNextTime() + requestLimit.second() * 1000);
            } else {
                temp.setCount(temp.getCount() + 1);
                temp.setCurTime(System.currentTimeMillis());
                request.getSession().setAttribute(limitKey, temp);
            }
        }
        return false;
    }
}
